package com.example.lycdays.ui.login;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lycdays.BaseApplication;
import com.example.lycdays.R;
import com.example.lycdays.data.bean.Result;
import com.example.lycdays.data.bean.User;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "myTag";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private String URL;

    EditText textViewUserName, textViewPassword;
    Button buttonLogin, buttonRegister;

    User user = null;
    Result result = null;
    private String username;
    private String password;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Toolbar toolbar = findViewById(R.id.toolbarLogin);
        toolbar.setTitleTextColor(getColor(R.color.colorWhite));
        toolbar.setTitle("登录/注册");
        setSupportActionBar(toolbar);

        URL = getString(R.string.URL);
        textViewUserName = findViewById(R.id.editText_username);
        textViewPassword = findViewById(R.id.editText_password);
        buttonLogin = findViewById(R.id.button_login);
        buttonRegister = findViewById(R.id.button_register);

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFinished()) {
                    Toast.makeText(LoginActivity.this, "请填写所有内容", Toast.LENGTH_SHORT).show();
                } else {
                    user = new User();
                    user.setUserName(username);
                    user.setPassword(password);
                    Gson gson = new Gson();
                    loginWithOkhttp(gson.toJson(user));

                }
            }
        });

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFinished()) {
                    Toast.makeText(LoginActivity.this, "请填写所有内容", Toast.LENGTH_SHORT).show();
                } else {
                    user = new User();
                    user.setUserName(username);
                    user.setPassword(password);
                    Gson gson = new Gson();
                    registWithOkhttp(gson.toJson(user));
                }
            }
        });
    }

    private void loginWithOkhttp(final String param) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, URL + "/user/login/");
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(JSON, param);
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url("http://" + URL + "/user/login")
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "data: " + responseData);

                    handleLoginResult(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void registWithOkhttp(final String param) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, URL + "/user/regist/");
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(JSON, param);
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url("http://" + URL + "/user/regist")
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "data: " + responseData);

                    handleRegistResult(responseData);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void handleLoginResult(final String responseData) {
        result = null;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                parseJSONWithGSON(responseData);
                if (result.isSuccess()) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    user.save();
                    BaseApplication.setIsRegister(true);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "登录失败，请检查账号密码", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }



    private void handleRegistResult(final String responseData) {
        result = null;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                parseJSONWithGSON(responseData);
                if (result.isSuccess()) {
                    Toast.makeText(LoginActivity.this, "注册成功，请点击登录", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, "注册失败，该账号已存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        result = gson.fromJson(jsonData, Result.class);
        Log.d(TAG, "data: " + result.getMsg());
    }



    /**
     * 判断用户的用户名和密码是否都输入
     * @return
     */
    private boolean isFinished() {
        username =  textViewUserName.getText().toString().trim();
        password = textViewPassword.getText().toString().trim();

        return !"".equals(username) && !"".equals(password);
    }
}
